package com.wanxi.spring.cloud.team.service.impl;

import com.wanxi.spring.cloud.commons.api.CommonResult;
import com.wanxi.spring.cloud.team.mapper.TeamMapper;
import com.wanxi.spring.cloud.team.feign.UserService;
import com.wanxi.spring.cloud.team.model.Team;
import com.wanxi.spring.cloud.team.model.User;
import com.wanxi.spring.cloud.team.model.UserRole;
import com.wanxi.spring.cloud.team.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 蒋帆
 * @since 2020-12-21
 */
@Service
public class TeamServiceImpl implements TeamService {

    @Autowired(required = false)
    TeamMapper teamMapper;
    @Autowired
    UserService userService;

    @Override
    public CommonResult getTeamList(Map map) {
        int page = (Integer.parseInt((String) map.get("page")) - 1) * Integer.parseInt((String) map.get("limit"));
        map.put("page", page);
        map.put("limit", Integer.parseInt((String) map.get("limit")));
        List<Team> teamList = teamMapper.getTeamList(map).stream().map(team -> {
            String teamLeader = team.getLeader();
            //判断该组长是否还在该组
            Team leader = teamMapper.teamLeaderJudge(team.getId());
            if (leader==null) {//如果不在了
                team.setLeader("");//清空该小组组长字段
                team.setLeaderName("");
                teamMapper.clearTeamLeader(team.getId());//数据库清空该小组组长字段
                if (teamLeader!=""&&teamLeader!=null) {
                    User user = userService.getUserByName(teamLeader);
                    UserRole userRole = new UserRole();
                    userRole.setUser(user.getId()).setRole(1);
                    userService.updateUserRole(userRole);
                }
            }
            return team;
        }).collect(Collectors.toList());
        long count = teamMapper.getTeamCount(map);
        return CommonResult.success(teamList,count);
    }

    @Override
    public CommonResult getTeamByName(String name) {
        Team team = teamMapper.getTeamByName(name);
        return CommonResult.success(team);
    }

    @Override
    public CommonResult deleteTeam(Integer id) {
        int result = teamMapper.deleteTeam(id);
        if (result>0)
            return CommonResult.success(result,"删除成功");
        return CommonResult.failed("删除失败");
    }

    @Override
    public CommonResult updateTeam(Team team) {
        int result = teamMapper.updateTeam(team);
        if (result> 0) {
            return CommonResult.success(result, "修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    @Override
    public int addTeam(Team team) {
        return teamMapper.addTeam(team);
    }

}
